const query = require('../db/index');
const moment = require('moment');

class ArticleController {
    static instance;
    static getInstance () {
        if (!this.instance) {
            this.instance = new ArticleController();
        }
        return this.instance;
    }
    async createArticle (req, res, next) {
        console.log('queryRes', req.body);
        try {
            const querytSql = 'select * from ev_article_cate  where name = ?  and alias = ?  and is_delete!=1 ';
            const querytParams = [req.body.name, req.body.alias];
            const queryRes = await query(querytSql, querytParams);
            console.log('queryRes', queryRes);
            if (queryRes.length > 0) {
                return res.err('文章名或文章别名被占用，请重新创建');
            }
            const insertSql = 'insert into ev_article_cate (name,alias,auth,create_time) values(?,?,?,?) ';
            const insertParams = [
                req.body.name,
                req.body.alias,
                req.body.auth,
                moment().format('YYYY-MM-DD HH:mm:ss')
            ];
            const insertRes = await query(insertSql, insertParams);
            if (insertRes && insertRes.affectedRows > 0) {
                res.json({
                    code: 200,
                    msg: '创建文章成功',
                    data: true
                });
            } else {
                res.err('创建文章失败');
            }
        } catch (error) {
            console.log('error', error);
            res.err(error, 500);
        }
    }
    async getArticleList (req, res, next) {
        try {
            const countSql = 'SELECT count(id) as total FROM ev_article_cate WHERE is_delete!=1';
            const [{ total }] = await query(countSql);
            if (total < (req.body.pageNo - 1) * req.body.pageSize) return res.err('暂无更多数据');
            const sql = 'select * from ev_article_cate where is_delete!=1  limit ?,?';
            const params = [
                (req.body.pageNo - 1) * req.body.pageSize,
                req.body.pageNo * req.body.pageSize - 1
            ];
            const result = await query(sql, params);

            console.log('result', result, total);
            if (result && result.length > 0) {
                res.json({
                    code: 200,
                    msg: '查询文章成功',
                    data: {
                        list: result,
                        total
                    }
                });
            } else {
                res.err('查询文章失败');
            }
        } catch (error) {
            console.log('error', error);
            res.err(error, 500);
        }
    }
    async modifyArticle (req, res, next) {
        console.log('body', req.body);
        try {
            if (!req.body.id) return res.err('请选择更新文章');
            const selectSql = 'select * from ev_article_cate where id = ? and is_delete != 1 and (name = ? or alias = ?)';
            const selectParams = [
                req.body.id,
                req.body.name,
                req.body.alias
            ];
            const selectRes = await query(selectSql, selectParams);
            if (selectRes && selectRes.length > 0) return res.err('改文章name或alias已存在，更新失败');
            const ev_article_cate = [{
                name: 'name',
                value: 'name'
            }, {
                name: 'alias',
                value: 'alias',
            }, {
                name: 'auth',
                value: 'auth'
            }, {
                name: 'createTime',
                value: 'create_time'
            }];
            let upSql = '';
            const params = [];
            ev_article_cate.forEach((item, index) => {
                console.log('req.body[item.name]', item.name, req.body[item.name]);
                if (req.body[item.name]) {
                    upSql += `${item.value} =?,`;
                    params.push(req.body[item.name]);
                }
            });
            params.push(+req.body.id, req.body);
            if (!upSql) return res.err('请添加更新内容');
            const sql = 'update ev_article_cate set ' + upSql.slice(0, upSql.length - 1) + 'where id = ? and is_delete != 1';
            console.log('params', sql);

            const result = await query(sql, params);
            if (result.affectedRows <= 0) return res.err(result.info);
            res.suc('更新文章');
        } catch (error) {
            console.log('error', error);
            res.err(error, 500);
        }
    }
    async deleteArticle (req, res, next) {
        try {
            const sql = 'update ev_article_cate set is_delete = 1 where is_delete != 1 and id = ? ';
            const params = [req.body.id];
            const result = await query(sql, params);
            console.log('result', result);
            if (result && result.affectedRows <= 0) return res.err('该文章不存在，删除失败');
            res.suc('删除文章');
        } catch (error) {
            console.log('error', error);
            res.err(error, 500);
        }
    }
    async getArticleDetail (req, res, next) {
        try {
            const sql = 'select * from  ev_article_cate where is_delete != 1 and id = ?';
            const params = [req.body.id];
            const result = await query(sql, params);
            console.log('result', result);
            if (result && result.length <= 0) return res.err('获取文章详情失败');
            res.json({
                code: 200,
                data: result,
                msg: '获取文章详情成功'
            });
        } catch (error) {
            console.log('error', error);
            res.err(error, 500);
        }
    }
}
module.exports = ArticleController.getInstance();